#   ============================================================================
#   Youhua Xu May-5-2021
#   ============================================================================
#   Make a build dir for compilation
MDIR := $(shell pwd)
WRKDIR = $(MDIR)/build
BINDIR = $(MDIR)/bin

#	make build & binary dirs
.base:
	if ! [ -e $(WRKDIR) ]; then mkdir $(WRKDIR) ; fi;
	touch $(WRKDIR)/.base;
	if ! [ -e $(BINDIR) ]; then mkdir $(BINDIR) ; fi;
	touch $(BINDIR)/.base;
#   ============================================================================
#   Set the source file path
vpath %.c   main:src:tests
vpath %.h   include
vpath %.o build
vpath .base build

INCLUDES = -I $(MDIR)/include

CC			= gcc
CCFLAG  	= -Wall #-O3  # 在DPM上，如果打开-O3，无法正常写入头文件中的参数
OPTFLAG		= #-O2 #-ffast-math #( not recognized by intel compiler )
LIBS		= -lm -lcfitsio #-lgsl -lgslcblas 
LDFLAG      = 

# add options for debug
# CCFLAG		+= -D_PRINT_A_LINE_ -D_DEBUG_LINE_NUM_=100 # output 100th row when doing CDS 
# CCFLAG		+= -D_DEBUG_INI_ # write loaded ini contents into ini_debug.ini
# CCFLAG		+= -D_WRITE_LINE_TAG_ # write line number into line_tag.txt

CCFLAG      += -D_DEBUG_FITS_HEADER_

#   http://www.tuicool.com/articles/NBfeYj
ifeq ($(shell uname -s),Linux)
	LDFLAG	+= -Wl,--no-as-needed
#	CC		= arm-linux-gnueabihf-gcc
	CC		= gcc
endif

ifeq ($(shell uname -s),Darwin)
	LDFLAG	+= -framework Accelerate #(-framework Accelerate is for Mac OSX)
	CC		= gcc
endif

%.o: %.c .base
	cd $(WRKDIR);$(CC) $(OMPFLAG) $(OPTFLAG) $(CCFLAG) $(INCLUDES) -c ../$< -o $*.o

MAIN_BIN2FITS 	= bin2fits.o
MAIN_BIN2WAVE	= bin2wave.o
EXTRACT 	= extract_ccd290.o extract_ccd290_uint16.o extract_ccd290_flt.o extract_ccd290_csst.o extract_waveform.o
DEPS		= dictionary.o iniparser.o misc.o \
			  get_waveform_ob_tag.o ccd290_config.o extract_waveform_config.o\
			  get_waveform_ob_tag_no_shift.o add_fits_keywords_from_ini.o

MAIN_GET_WF_OB = get_waveform_ob.o

all: bin2fits bin2wave get_waveform_ob


bin2fits: ${MAIN_BIN2FITS} ${EXTRACT} ${DEPS}
	${CC} ${OPTFLAG} ${LDFLAG} $(addprefix build/,$(notdir $^)) ${LIBS} -o $(BINDIR)/$@

bin2wave: ${MAIN_BIN2WAVE} ${EXTRACT} ${DEPS}
	${CC} ${OPTFLAG} ${LDFLAG} $(addprefix build/,$(notdir $^)) ${LIBS} -o $(BINDIR)/$@

get_waveform_ob: ${MAIN_GET_WF_OB} ${EXTRACT} ${DEPS}
	${CC} ${OPTFLAG} ${LDFLAG} $(addprefix build/,$(notdir $^)) ${LIBS} -o $(BINDIR)/$@

.PHONY:clean tidy run
clean: .base
	rm -rf $(WRKDIR);
tidy:
	make clean; rm -rf $(BINDIR) $(WRKDIR)
